package org.example.spring.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.example.spring.context.BaseContext;
import org.example.spring.entity.DTO.LoginDTO;
import org.example.spring.entity.User;
import org.example.spring.entity.VO.LoginVO;
import org.example.spring.exception.BaseException;
import org.example.spring.mapper.UserMapper;
import org.example.spring.service.IUserService;
import org.example.spring.utils.JWTUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        QueryWrapper queryWrapper=new QueryWrapper<>().eq("account",loginDTO.getAccount());
        User one = getOne(queryWrapper);
        if(one==null){
            throw new BaseException("该用户不存在！");
        }
        if(!one.getPassword().equals(loginDTO.getPassword())){
            throw new BaseException("密码错误！");
        }
        //下发令牌
        Map<String,Object> claims=new HashMap<>();
        claims.put("account",one.getAccount());
        claims.put("id",one.getId());
        String s = JWTUtils.generateJwt(claims);
        LoginVO loginVO = new LoginVO();
        loginVO.setName(one.getName());
        loginVO.setImg(one.getImg());
        loginVO.setToken(s);
        loginVO.setAccount(one.getAccount());
        return loginVO;
    }

    @Override
    public void register(LoginDTO loginDTO) {
        String account= loginDTO.getAccount();
        QueryWrapper queryWrapper=new QueryWrapper<>().eq("account",account);
        User one = getOne(queryWrapper);
        if (one!=null){
            throw new BaseException("该用户名已被注册！");
        }
        User user = new User();
        user.setAccount(loginDTO.getAccount());
        user.setPassword(loginDTO.getPassword());
        save(user);
    }
}
